<?php
defined('SEJUJOPEFDNGJSL') or exit('Access denied');

function fun_deluser($kid)
{
    global $db, $GLOBALARR, $member, $r;
    $karr = array();
    try {
        $db->begintransaction();
        $sql = "select id,uname,user_level,introducer_id,parents_ids,leader_number,cash_purse,benifit_purse from ld_user_account where user_level=0 and recommend_unum=0 and id in($kid) order by id asc";
        $db->query($sql);
        $rs = $db->rs;
        foreach ($rs as $k => $v) {
            if ($member->downtu_exists($v['parents_ids']))
                a_bck($v['uname'] . "的下级还有未开通的会员，请先删除下级");
            $db->sitedbexec('delete from ld_user_account where id=' . $v['id']);
            $karr[] = $v["uname"];
        }
        $db->committransaction();
        $db->sitedbexec('delete from ld_user_info where id in(' . $kid . ')');
    } catch (PDOException $e) {
        $db->rollbacktransaction();
        a_bck("error");
    }
    return $karr;
}

// 开通会员
function fun_openuser($kid, $opid, $flag)
{
    global $db, $GLOBALARR, $member, $r;
    $karr = array();

    try {
        $db->begintransaction();
        $rt = fun_insertTime();

        $sql = "select id,uname,user_level,introducer_id,parents_ids,leader_number,cash_purse,benifit_purse,openuser_cost_coin,active_coin from ld_user_account where is_passed=0 and id in($kid) order by id asc";
        $db->query($sql);
        $rs = $db->rs;
        foreach ($rs as $k => $v) {

            if (!$flag) {
                if ($r['active_coin'] < $v["openuser_cost_coin"]) {
                    a_bck("您的激活币账户余额不足 " . $v["openuser_cost_coin"]);
                    exit();
                }
                writeaccount(array(
                    $opid,
                    "1",
                    3,
                    time(),
                    8,
                    $v["openuser_cost_coin"],
                    '开通' . $v["uname"]
                ));
            }

            if ($member->upperuser_exists($v['parents_ids']))
                a_bck($v['uname'] . "的上级还有未开通的会员，请先开通上级");

            $kdate = time();
            $ktr = $opid . '|' . $flag;
            // 更新账户激活 开通时间 开通人 开通期数
            $db->lspre("update ld_user_account set is_passed=1,open_time=:t1,opener_uname=:t2,open_classify=:t3 where id=:t0", 4, array(
                array(
                    ':t0',
                    ':t1',
                    ':t2',
                    ':t3'
                ),
                array(
                    $v['id'],
                    $kdate,
                    $ktr,
                    $rt['id']
                )
            ));
            // 开通人的直推数+1
            $db->lspre("update ld_user_account set recommend_unum=recommend_unum+1 where id=:t0", 4, array(
                array(
                    ':t0'
                ),
                array(
                    $v['introducer_id']
                )
            ));
            $leader = $member->getuv1($v['introducer_id'], 'user_level');

            // 团队加
            $db->query("update ld_user_account set team_number=team_number+1 where id in(0" . $v["parents_ids"] . "0)", 4);
            // 用户升级条件
            fun_sj($v["introducer_id"]);

            $karr[] = $v["uname"];
        }

        $db->committransaction();
    } catch (PDOException $e) {
        $db->rollbacktransaction();
        a_bck("error");
    }

    return $karr;
}

// 过滤html<>标签
function htmlguolv($c)
{
    $str = preg_replace("/<(.*?)>/", '', htmlspecialchars_decode($c));
    // $pattern='/<p>*/';
    // $content=preg_replace($pattern,'',$c);
    return $str;
}


// 得到特定文章内容
function get_article($title)
{
    global $db;
    $title = trim($title);
    $sql = "select * from ld_article where is_show=0 and attype=0 and title='" . $title . "'";
    $db->query($sql, 2);
    $cpl = $db->rs;
    $cont = htmlspecialchars_decode($cpl['content']);
    return $cont;
}

// 用户注册页面显示的人数（根据要求显示）
function get_regnum()
{
    global $db;
    $sql = "select count(*) as n from ld_user_account";
    $db->query($sql, 2);
    $num = $db->rs;
    return $num['n'];
}

// 将parends_ids字段转为数组
function par_arr($str)
{
    $pas = trim($str, ',');
    if ($pas == '') { // 若字段为,返回array(0=>0)
        return $parr = array(
            0 => 0
        );
    } else if (strpos($pas, ',') === false) { // 若字段值为 ,655, 返回array(0=>655)
        return $parr = array(
            0 => $pas
        );
    }
    return $parr = explode(',', $pas);
}

// 根据用户uid取得该用户n级上线id集合
function get_nsx($uid, $n = 0)
{
    global $db;
    $sql = "select id,parents_ids from ld_user_account where id=" . $uid;
    $db->query($sql);
    $pas = $db->rs[0]['parents_ids'];
    if (trim($pas) == ',') {
        return false;
    }
    $parr = par_arr($pas);
    if ($n != 0) {
        if (count($parr) == 1) { // 若只有一级上线，返回1级
            return $parr;
        } else if (count($parr) >= 2) { // 大于等于2级上线，返回2级
            $parr = array_slice($parr, -$n, $n);
        }
    }
    return $parr;
}

// 根据用户uid获取该用户n级下线id集合
function get_nxx($uid, $n = 10000000)
{
    global $db;
    $db->query("select id,parents_ids,find_in_set('" . $uid . "',parents_ids) as dai from ld_user_account where is_passed = 1 and is_freezed = 0");
    $users = $db->rs;
    $list = array();
    if (!empty($users)) {
        foreach ($users as $key => $v) {
            $zong_dai = substr_count($v['parents_ids'], ",");
            if ($v['dai'] > 0) {
                $the_dai = $zong_dai - $v['dai'] + 1;
            } else {
                $the_dai = 0;
            }
            if ($the_dai > 0 && $the_dai <= $n) {
                array_push($list, $v['id']);
            }
        }
    }
    return $list;
}

// 根据用户uid获取该用户同一直接上线的用户
function get_tsx($uid)
{
    if ($uid == 8501) { // 对于admin,该类型只有他本身
        return array(
            0 => 8501
        );
    }
    $suid = get_nsx($uid, 1);
    $list = get_nxx($suid[0], 1);
    return $list;
}


// 发放奖励的时间是当前天的23点59分59秒
function fun_insertTime()
{
    global $db, $GLOBALARR;
    $xian = date("Y-m-d", time());
    // 今天的23点59分59秒
    $x = strtotime($xian . " 23:59:59");
    // 选取grant_prize表的倒数第一条记录
    $db->query("select * from ld_grant_prize order by id desc limit 1", 2);

    if (empty($db->rs)) {
        // 如果没有记录插入一条
        $db->sitedbexec("insert into ld_grant_prize(grant_time) values(" . $x . ")");
    } else {
        // 如果今天的23点59分59秒在grant_time之后（也就相当于最近的一条记录也在昨天）
        if ($x > $db->rs['grant_time']) {
            // 插入一条新记录

            $db->sitedbexec("insert into ld_grant_prize(grant_time) values(" . $x . ")");
            // 奖金记录列表id更新成0
            $db->sitedbexec("update ld_user_account set pg_id=0 where pg_id>0");
        }
    }
    $db->query("select * from ld_grant_prize order by id desc limit 1", 2);
    return $db->rs;
}

// 计算一天内的总收益和总奖金
function fun_totalPrice()
{
    global $db, $GLOBALARR, $member, $r;
    $db->query("select * from ld_grant_prize order by id desc limit 1", 2);
    $rt = $db->rs;
    $wsql = " where (sf_amount!=0 or lx_amount!=0 or ld_amount!=0 or sy_amount!=0 or yj_amount!=0) and is_passed>0";
    $sql = "select sf_amount,lx_amount,ld_amount,sy_amount,yj_amount,id,uname,pg_id,pt_record_mark,user_level from ld_user_account " . $wsql;
    $db->query($sql);
    $rs = $db->rs;
    foreach ($rs as $k => $v) {
        $sf_amount = getfnum($v["sf_amount"]);
        $lx_amount = getfnum($v["lx_amount"]);
        $ld_amount = getfnum($v["ld_amount"]);
        $sy_amount = getfnum($v["sy_amount"]);
        $yj_amount = getfnum($v["yj_amount"]);

        // 写入prize_gather表
        if (empty($v["pg_id"])) {
            $sql = "insert into ld_prize_gather(prize_sf,prize_lx,prize_ld,prize_sy,prize_yj,uid,prize_record_time,veid,prize_give_time) values(:t1,:t2,:t3,:t4,:t5,:t6,:t7,:t8,:t9)";
            $db->lspre($sql, 5, array(
                array(
                    ':t1',
                    ':t2',
                    ':t3',
                    ':t4',
                    ':t5',
                    ':t6',
                    ':t7',
                    ':t8',
                    ':t9'
                ),
                array(
                    $sf_amount,
                    $lx_amount,
                    $ld_amount,
                    $sy_amount,
                    $yj_amount,
                    $v['id'],
                    time(),
                    $rt['id'],
                    $rt['grant_time']
                )
            ));
            // 更新用户表记录prize_gather_id
            $sql = "update ld_user_account set pg_id=:t1 where id=:t0";
            $db->lspre($sql, 4, array(
                array(
                    ':t0',
                    ':t1'
                ),
                array(
                    $v['id'],
                    $db->fval
                )
            ));
        } else {
            // 更新prize_gather表
            $sql = "update ld_prize_gather set prize_sf=prize_sf+:t1,prize_lx=prize_lx+:t2,prize_ld=prize_ld+:t3,prize_sy=prize_sy+:t4,prize_yj=prize_yj+:t5 where pgid=:t0";
            $db->lspre($sql, 4, array(
                array(
                    ':t0',
                    ':t1',
                    ':t2',
                    ':t3',
                    ':t4',
                    ':t5'
                ),
                array(
                    $v["pg_id"],
                    $sf_amount,
                    $lx_amount,
                    $ld_amount,
                    $sy_amount,
                    $yj_amount
                )
            ));
        }

        // 写入prize_total表
        if (empty($v["pt_record_mark"])) {
            $sql = "insert into ld_prize_total(t_prize_sf,t_prize_lx,t_prize_ld,t_prize_sy,t_prize_yj,uname,prize_gtime) values(:t1,:t2,:t3,:t4,:t5,:t6,:t7)";

            $db->lspre($sql, 4, array(
                array(
                    ':t1',
                    ':t2',
                    ':t3',
                    ':t4',
                    ':t5',
                    ':t6',
                    ':t7'
                ),
                array(
                    $sf_amount,
                    $lx_amount,
                    $ld_amount,
                    $sy_amount,
                    $yj_amount,
                    $v['uname'],
                    time()
                )
            ));

            $sql = "update ld_user_account set pt_record_mark=1 where id=:t0";
            $db->lspre($sql, 4, array(
                array(
                    ':t0'
                ),
                array(
                    $v['id']
                )
            ));
        } else {
            // 更新prize_total表
            $sql = "update ld_prize_total set t_prize_sf=t_prize_sf+:t1,t_prize_lx=t_prize_lx+:t2,t_prize_ld=t_prize_ld+:t3,t_prize_sy=t_prize_sy+:t4,t_prize_yj=t_prize_yj+:t5 where uname=:t0";
            $db->lspre($sql, 4, array(
                array(
                    ':t0',
                    ':t1',
                    ':t2',
                    ':t3',
                    ':t4',
                    ':t5'
                ),
                array(
                    $v["uname"],
                    $sf_amount,
                    $lx_amount,
                    $ld_amount,
                    $sy_amount,
                    $yj_amount
                )
            ));
        }

        // 更新用户表，增加利息收益，推广提成
        $sql = "update ld_user_account set total_prize=total_prize+:t1,benifit_purse=benifit_purse+:t2,commission_purse=commission_purse+:t3 where id=:t0";
        $db->lspre($sql, 4, array(
            array(
                ':t0',
                ':t1',
                ':t2',
                ':t3'
            ),
            array(
                $v['id'],
                0,
                $sy_amount,
                $yj_amount
            )
        ));
    }

    // 更新用户表，金额全部清零
    $wsql = " where (sf_amount!=0 or lx_amount!=0 or ld_amount!=0 or sy_amount!=0 or yj_amount!=0) and is_passed>0";
    $db->sitedbexec("update ld_user_account set sf_amount=0,lx_amount=0,ld_amount=0,sy_amount=0,yj_amount=0 " . $wsql);
}


// 用户升级动态奖
function fun_sj($id)
{
    global $db, $GLOBALARR, $member, $r;
    if (empty($id))
        return;
    // 防止刷新页面太快 导致后期加载的慢
    if (is_file("funsj/" . $id . ".txt")) {
        $xx = file_get_contents("funsj/" . $id . ".txt");
    } else {
        $xx = '';
        file_put_contents("funsj/" . $id . ".txt", time());
    }
    if (!empty($xx) && time() - $xx < 5) {
        return;
    } else {
        file_put_contents("funsj/" . $id . ".txt", '');
        file_put_contents("funsj/" . $id . ".txt", time());
    }

    $db->query("select user_level,id,uname from ld_user_account where id=$id", 2);
    $rs = $db->rs;
    $zhitui = yes_zhitui($rs['id']);
    // echo $zhitui;
    // exit;
    $zhuan = 0;
    switch ($rs["user_level"]) {
        case 0:
            if ($zhitui >= $GLOBALARR['jjsjt'][0]) {
                $db->sitedbexec("update ld_user_account set user_level=1 where id=" . $rs["id"]);
            }
            break;
        case 1:
            if ($zhitui >= $GLOBALARR["jjsjt"][1]) {
                $db->sitedbexec("update ld_user_account set user_level=2 where id=" . $rs["id"]);
            }
            break;
        case 2:
            break;
    }
    // 降级 auto
    switch ($rs["user_level"]) {
        case 0:
            break;
        case 1:
            if ($zhitui < $GLOBALARR['jjsjt'][0]) {
                $db->sitedbexec("update ld_user_account set user_level=0 where id=" . $rs["id"]);
            }
            break;
        case 2:
            if ($zhitui < $GLOBALARR["jjsjt"][1]) {
                $db->sitedbexec("update ld_user_account set user_level=1 where id=" . $rs["id"]);
            }
            break;
    }
}

// 用户的晋级奖
function fun_jj($id)
{
    global $db, $GLOBALARR, $member, $r;
    if (empty($id))
        return;
    $db->query("select user_jjlever,id,uname from ld_user_account where id=$id", 2);
    $rs = $db->rs;
    $zhitui = yes_zhitui($rs['id']);
    $team = yes_team_num($rs['id'], $rs['user_jjlever']);
    $tot = $team[0];
    $num = $team[1];
    $jjnum = $team[2];
    $fa = 0;
    $bli = 0;
    if ($rs['user_jjlever'] > 0) {
        $teams = yes_team_num($rs['id'], $rs['user_jjlever'] - 1);
        $tot1 = $teams[0];
        $num1 = $teams[1];
        $jjnum1 = $teams[2];
    }
    // 1银牌经理2金牌经理3钻石经理
    switch ($rs["user_jjlever"]) {
        case 0:
            if ($zhitui >= $GLOBALARR['jjzt'][0] && $tot >= $GLOBALARR['jjtd'][0] && $num >= $GLOBALARR['jjnum'][0]) {
                $db->sitedbexec("update ld_user_account set user_jjlever=1 where id=" . $rs["id"]);
            }
            break;
        case 1:
            if ($zhitui >= $GLOBALARR["jjzt"][1] && $tot >= $GLOBALARR['jjtd'][1] && $jjnum >= $GLOBALARR['jjnum'][1]) {
                $db->sitedbexec("update ld_user_account set user_jjlever=2 where id=" . $rs["id"]);
            }
            if ($zhitui < $GLOBALARR['jjzt'][0] || $tot < $GLOBALARR['jjtd'][0] || $num1 < $GLOBALARR['jjnum'][0]) {
                $db->sitedbexec("update ld_user_account set user_jjlever=0 where id=" . $rs["id"]);
            }
            break;
        case 2:
            if ($zhitui >= $GLOBALARR["jjzt"][2] && $tot >= $GLOBALARR['jjtd'][2] && $jjnum >= $GLOBALARR['jjnum'][2]) {
                $db->sitedbexec("update ld_user_account set user_jjlever=3 where id=" . $rs["id"]);
            }
            if ($zhitui < $GLOBALARR["jjzt"][1] || $tot < $GLOBALARR['jjtd'][1] || $jjnum1 < $GLOBALARR['jjnum'][1]) {
                $db->sitedbexec("update ld_user_account set user_jjlever=1 where id=" . $rs["id"]);
            }
            break;
        case 3:
            if ($zhitui < $GLOBALARR["jjzt"][2] || $tot < $GLOBALARR['jjtd'][2] || $jjnum1 < $GLOBALARR['jjnum'][2]) {
                $db->sitedbexec("update ld_user_account set user_jjlever=2 where id=" . $rs["id"]);
            }
            break;
    }
}

// 取得用户的有效（挂过单并且状态不是未激活也不是已被封）直推人数
function yes_zhitui($uid)
{
    global $db, $member;
    $db->query("select * from ld_user_account where is_passed = 1 and is_freezed = 0 and introducer_id = " . $uid);
    $fellows = $db->rs;
    $zhitui = 0;
    if (!empty($fellows)) {
        foreach ($fellows as $val) {
            if (yes_give_help($val['id']) && yes_ti_benjin($val['id'])) { // 用户是否提本金
                $zhitui++;
            }
        }
    }
    return $zhitui;
}

// 取得用户的有效团队数
function yes_team_num($uid, $jjlevel)
{
    global $db, $GLOBALARR;
    // 查找有多少个直推 然后从直推算起每一条线的销售业绩
    $tot = 0;
    $bum = 0;
    $ever = 0;
    $team = 0;
    $db->query("select id,find_in_set('" . $uid . "',parents_ids) as dai,benifit_purse from ld_user_account where is_passed = 1 and give_help_time>0 and is_freezed = 0 or id=" . $uid); // find_in_set 查找id在字符串中出现的位置
    $users = $db->rs;
    if (!empty($users)) {
        foreach ($users as $v) {
            if (!empty($v['dai']) || $v['id'] == $uid) {
                $tot = $tot + $v['benifit_purse'];
                $team++;
            }
        }
    }
    // 更新一下团队奖
    $db->query("update ld_user_account set team_tot=" . $tot . ",team_number=" . $team . " where id=" . $uid, 4);
    // 先找出直推会员有几个来
    $db->query("select id from ld_user_account where introducer_id=" . $uid . "");
    $ztlist = $db->rs;
    if ($jjlevel == 0) {
        if ($ztlist) {
            foreach ($ztlist as $key => $v) {
                $db->query("select id,find_in_set('" . $v['id'] . "',parents_ids) as dai,benifit_purse,user_jjlever from ld_user_account where is_passed = 1 and give_help_time>0 and is_freezed = 0 or id=" . $v['id']); // find_in_set 查找id在字符串中出现的位置
                $team = $db->rs;
                $cytot = 0;
                if (!empty($team)) {
                    foreach ($team as $vv) {
                        if (!empty($vv['dai']) || $vv['id'] == $v['id']) {
                            $cytot = $cytot + $vv['benifit_purse'];
                        }
                    }
                }

                if ($cytot >= $GLOBALARR['cy_amount']) {
                    $ever++;
                }
            }
        }
    } else {
        if ($ztlist) {
            foreach ($ztlist as $key => $v) {
                $db->query("select id,find_in_set('" . $v['id'] . "',parents_ids) as dai,benifit_purse,user_jjlever from ld_user_account where is_passed = 1 and give_help_time>0 and is_freezed = 0 or id=" . $v['id']); // find_in_set 查找id在字符串中出现的位置
                $team2 = $db->rs;
                $status = 0;
                if (!empty($team2)) {
                    foreach ($team2 as $vv) {
                        if (!empty($vv['dai']) || $v['id'] == $vv['id']) {
                            if ($vv['user_jjlever'] >= $jjlevel) {
                                $status = 1;
                                break;
                            }
                        }
                    }
                }
                if ($status == 1) {
                    $bum++;
                }
            }
        }
    }

    return array(
        $tot,
        $ever,
        $bum
    );
}

// 取得用户是否挂过单
function yes_give_help($uid)
{
    global $db, $member;
    $db->query("select count(*) as gdnum from ld_give_help where `status` < 3 and uid = " . $uid, 2);
    $gdnum = $db->rs['gdnum'];
    if (!empty($gdnum)) {
        return true;
    } else {
        return false;
    }
}

// 是否提过共享积分
function yes_ti_benjin($uid)
{
    global $db, $member;
    $db->query("select count(*) as gdnum from ld_transfer_coin where `ctype` = 0 and type=0 and is_cross=1  and cuid = " . $uid, 2);
    $gdnum = $db->rs['gdnum'];
    if (!empty($gdnum)) {
        return false;
    } else {
        return true;
    }
}

function fun_jjxx1($arr)
{
    global $db, $GLOBALARR, $member, $r;
    if (empty($arr[7])) {
        $arr[7] = 0;
    }
    if (empty($arr[8])) {
        $arr[8] = 0;
    }
    $sql = "insert into ld_prize_list(uid,veid,prize_ltime,prize_option,amount,description,help_id,lx_generation,prize_status) values(:t1,:t2,:t3,:t4,:t5,:t6,:t7,:t8,:t9)";
    $db->lspre($sql, 4, array(
        array(
            ':t1',
            ':t2',
            ':t3',
            ':t4',
            ':t5',
            ':t6',
            ':t7',
            ':t8',
            ':t9'
        ),
        array(
            $arr[0],
            $arr[1],
            $arr[2],
            $arr[3],
            $arr[4],
            $arr[5],
            $arr[6],
            $arr[7],
            $arr[8]
        )
    ));
}

// 发放给上线领导奖
function fun_jdjshouyi($id)
{
    global $db, $GLOBALARR, $member, $r;
    // 根据id选取状态是等待打款的提供帮助信息
    $sql = "select * from ld_give_help where `status`=1 and id=" . $id;
    $db->query($sql);
    $rs = $db->rs;
    foreach ($rs as $k => $v) {
        // 根据提供帮助id选取和利息无关的prize_list表里的记录
        $db->query("select uid,sum(amount) as amount from ld_prize_list where prize_status=0 and prize_option=52 and help_id=" . $v["id"] . " group by uid");
        $all = $db->rs;
        // 更新prize_list表，设置奖励状态为无效（已奖励）
        $db->lspre("update ld_prize_list set prize_status=1,children_prize_mark=1,delay_mark_time=" . time() . " where prize_status=0 and prize_option=52 and help_id=:t0", 4, array(
            array(
                ':t0'
            ),
            array(
                $v["id"]
            )
        ));
        foreach ($all as $kk => $vv) {
            if ($vv["amount"] > 0) {
                // 增加历史奖金总额
                $db->lspre("update ld_user_account set total_prize=total_prize+:t1 where id=:t0", 4, array(
                    array(
                        ':t0',
                        ':t1'
                    ),
                    array(
                        $vv["uid"],
                        $vv["amount"]
                    )
                ));
                // 减佣金钱包
                writeaccount(array(
                    $vv["uid"],
                    "1",
                    2,
                    time(),
                    19,
                    $vv["amount"],
                    '领导奖转入可提领导奖余额-提供帮助编号|' . $v['give_help_no']
                ));
                // 加可提领导奖钱包
                writeaccount(array(
                    $vv["uid"],
                    "0",
                    9,
                    time(),
                    19,
                    $vv["amount"],
                    '领导奖转入-提供帮助编号|' . $v['give_help_no']
                ));
            }
        }
    }
}

// 指定会员获取收益
function fun_autoshouyi($give_help_uname)
{
    global $db, $GLOBALARR, $member, $r;
    // 选取收益状态是-收益结束-并且没有获取过收益-并且状态不是等待配对或已取消-并且获得帮助人超时未确认标记-并且已配对金额等于提供帮助金额-并且配对结束时间大于系统设定的提供获得帮助确认期限乘以2-的提供帮助记录
    $sql = "select * from ld_give_help where status_value<2 and had_shouyi=0 and status=1 and get_helper_unconfirm = 1 and matched_amount = amount and uname = '" . $give_help_uname . "' and TIMESTAMPDIFF(minute , from_unixtime(matched_time,'%Y-%m-%d %H:%i:%S'),  '" . date("Y-m-d H:i:s") . "')>" . (2 * $GLOBALARR["jjqkok"]);
    $db->query($sql);
    $rs = $db->rs;
    foreach ($rs as $k => $v) {
        // 更改记录为已获取收益
        $db->sitedbexec("update ld_give_help set status_value=2,get_helper_unconfirm=0,helper_confirm_amount = amount,had_shouyi=1,status=2,giveh_eviup_time=" . time() . " where id=" . $v["id"]);
        // 增加累计提供帮助金额
        $db->sitedbexec("update ld_user_account set sum_deposit=sum_deposit+" . $v["amount"] . " where id=" . $v["uid"]);
        $jin = $v["benifit_amount"] + $v["amount"];
        if ($jin > 0) {
            // 增加总奖金
            $db->lspre("update ld_user_account set total_prize=total_prize+:t1 where id=:t0", 4, array(
                array(
                    ':t0',
                    ':t1'
                ),
                array(
                    $v["uid"],
                    $jin
                )
            ));
            // 减掉利息收益
            writeaccount(array(
                $v["uid"],
                "1",
                1,
                time(),
                16,
                ($jin),
                '本息收益转入可提现余额-提供帮助编号|' . $v['give_help_no']
            ));
            // 增加可提现余额
            writeaccount(array(
                $v["uid"],
                "0",
                0,
                time(),
                16,
                ($jin),
                '本息收益转入-提供帮助编号|' . $v['give_help_no']
            ));
        }
        // 发放领导奖
        // 根据提供帮助id选取和利息无关的prize_list表里的记录
        $db->query("select uid,sum(amount) as amount from ld_prize_list where prize_status=0 and prize_option=52 and help_id=" . $v["id"] . " group by uid");
        $all = $db->rs;
        // 更新prize_list表，设置奖励状态为无效（已奖励）
        $db->lspre("update ld_prize_list set prize_status=1,children_prize_mark=1,delay_mark_time=" . time() . " where prize_status=0 and prize_option=52 and help_id=:t0", 4, array(
            array(
                ':t0'
            ),
            array(
                $v["id"]
            )
        ));
        foreach ($all as $kk => $vv) {
            if ($vv["amount"] > 0) {
                // 增加历史奖金总额
                $db->lspre("update ld_user_account set total_prize=total_prize+:t1 where id=:t0", 4, array(
                    array(
                        ':t0',
                        ':t1'
                    ),
                    array(
                        $vv["uid"],
                        $vv["amount"]
                    )
                ));
                // 减佣金钱包
                writeaccount(array(
                    $vv["uid"],
                    "1",
                    2,
                    time(),
                    19,
                    $vv["amount"],
                    '领导奖转入可提领导奖余额-提供帮助编号|' . $v['give_help_no']
                ));
                // 加可提领导奖钱包
                writeaccount(array(
                    $vv["uid"],
                    "0",
                    9,
                    time(),
                    19,
                    $vv["amount"],
                    '领导奖转入-提供帮助编号|' . $v['give_help_no']
                ));
            }
        }
        // 取得提供帮助人信息
        $row = $member->getuv($v["uname"], 'introducer_id,had_ghelp_mark,id,uname');
        if ($row["had_ghelp_mark"] == 0) {
            // 记录已经完成一次提供帮助
            $db->sitedbexec("update ld_user_account set had_ghelp_mark=1 where had_ghelp_mark=0 and id=" . $row["id"]);
        }
    }
}

// 更新实发金额
function fun_ks()
{
    global $db;
    $db->sitedbexec("update ld_user_account set sf_amount=lx_amount+ld_amount where is_passed>0 and (lx_amount!=0 or ld_amount!=0)");
}

// 记录上级本金提成
function fun_tjj($arr)
{
    global $db, $GLOBALARR, $member, $r;
    // 查询上级用户，前3条数据。根据追溯的层级和该层用户等级分配奖金。
    $sql = "select id,uname,user_level,parents_ids from ld_user_account where id in(0" . $arr[0] . "0) order by id desc limit 3";

    $db->query($sql);
    $rss = $db->rs;
    $oldqian = $arr[1];
    foreach ($rss as $k => $v) {
        $dui_status = is_duibi($v['id']);
        if ($dui_status == 0) {
            continue;
        }
        // 判断有木有排单 如果领导人木有排单则不产生领导奖
        $limit_amount = get_latest_give($v['id']);
        if ($limit_amount == 0) {
            continue;
        }
        $is_pai = get_is_pai($v['id']);
        if ($is_pai == 0) {
            continue;
        }

        $shaoshang = '';
        if ($oldqian > $limit_amount) {
            $qian = $limit_amount;
        } else {
            $qian = $oldqian;
            $shaoshang = '烧伤';
        }
        if ($v["user_level"] == 0) {
            if ($k == 0) {
                $lv = $GLOBALARR["jjtjj"][$k];
                $jin = $qian * $GLOBALARR["jjtjj"][$k] / 100;
            } else {
                $lv = 0;
                $jin = 0;
            }
        } elseif ($v["user_level"] == 1) {
            $lv = $GLOBALARR["jjtjj"][$k];
            $jin = $qian * $GLOBALARR["jjtjj"][$k] / 100;
        } elseif ($v["user_level"] == 2) {
            $lv = $GLOBALARR["jjtjj2"][$k];
            $jin = $qian * $GLOBALARR["jjtjj2"][$k] / 100;
        }
        if ($jin > 0) {

            // 写进prize_list表
            fun_jjxx1(array(
                $v['id'],
                $arr[3],
                time(),
                52,
                $jin,
                '第' . ($k + 1) . '代' . $arr[2] . '提供帮助' . $arr[1] . '的' . $lv . '%' . $shaoshang,
                $arr[4],
                ($k + 1)
            ));
        }
    }
}

// 记录晋级奖2/3
function fun_jinji($arr)
{
    global $db, $GLOBALARR, $member, $r;
    // 查询上级用户，前5条数据。根据追溯的层级和该层用户等级分配奖金。
    $sql = "select id,uname,user_jjlever,parents_ids from ld_user_account where id in(0" . $arr[0] . "0) order by id desc limit 20";
    $db->query($sql);
    $rss = $db->rs;
    $temp = array();
    $level = $arr[6];

    foreach ($rss as $k => $v) {
        if ($v['user_jjlever'] > $level) {
            $level = $v['user_jjlever'];
            array_push($temp, array(
                $v['id'],
                $v['user_jjlever'],
                $k
            ));
        }
    }
    if (empty($temp)) {
        return;
    }

    foreach ($temp as $key => $value) {
        $qian = $arr[1];
        $ldamount = get_pai_amount($value[0]);
        if ($qian > $ldamount) {
            $qian = $ldamount;
            $shaoshang = "烧伤";
        } else {
            $shaoshang = '';
        }

        if ($value[1] == 0) {
            $jin = 0;
            continue;
        } elseif ($value[1] == 1) {
            $lv = $GLOBALARR['jjjl'][0];
            $jin = $qian * $lv / 100;
        } elseif ($value[1] == 2) {
            $lv = $GLOBALARR['jjjl'][1];
            $jin = $qian * $lv / 100;
        } elseif ($value[1] == 3) {
            $lv = $GLOBALARR['jjjl'][2];
            $jin = $qian * $lv / 100;
        }
        if ($jin > 0) {
            // 更新用户表，增加本金提成和推广提成
            $sql = "update ld_user_account set ld_amount=ld_amount+:t1,yj_amount=yj_amount+:t2 where id=:t0";
            $db->lspre($sql, 4, array(
                array(
                    ':t0',
                    ':t1',
                    ':t2'
                ),
                array(
                    $value[0],
                    0,
                    $jin
                )
            ));

            // 写进prize_list表
            fun_jjxx1(array(
                $value[0],
                $arr[3],
                time(),
                62,
                $jin,
                $arr[2] . '消费排单' . $arr[1] . '的' . $lv . '%(晋级)' . $shaoshang,
                $arr[4],
                ($value[2] + 1)
            ));
        }
    }
}

function fun_rfhA()
{
    global $db, $GLOBALARR, $member;
    try {

        // 从提供帮助表中选择收益中的提供帮助用户等级值为0的收益次数小于最大收益次数的提供帮助记录
        $sql = "select amount,id,flx_time,give_help_time,give_help_no,benifit_times,uid,uname from ld_give_help where status=0 and (flx_time<" . time() . " or flx_time is NULL) and tctype='A'";
        $db->query($sql);
        $rs = $db->rs;
        if (!$rs) {
            return;
        }
        $db->begintransaction();
        $rt = fun_insertTime();
        foreach ($rs as $k => $v) {
            $rsm = $member->getuv1($v["uid"], "is_freezed");
            // 如果用户已被冻结跳过这次循环
            if ($rsm["is_freezed"] == 1)
                continue;
            if (empty($v['flx_time'])) {
                if (time() - $v['give_help_time'] < 24 * 3600) {
                    continue;
                }
            }
            if (date("Y-m-d") == date("Y-m-d", $v['flx_time'])) {
                continue;
            }
            // 金额等于设定的根据用户等级不同的不同利息乘以提供帮助金额
            $qian = $GLOBALARR['allowtxall'][0] / 100 * $v["amount"];
            // 收益次数加一
            $ci = $v['benifit_times'] + 1;

            $db->lspre("update ld_give_help set benifit_times=benifit_times+1,benifit_amount=benifit_amount+:t1,flx_time=" . time() . " where id=:t0", 4, array(
                array(
                    ':t0',
                    ':t1'
                ),
                array(
                    $v['id'],
                    $qian
                )
            ));
            if ($qian > 0) {
                // 写入prize_list表
                fun_jjxx1(array(
                    $v['uid'],
                    $rt['id'],
                    time(),
                    51,
                    $qian,
                    '锁仓编号' . $v["give_help_no"] . '第' . $ci . '次',
                    $v["id"],
                    0,
                    1
                ));
                writeaccount(array(
                    $v['uid'],
                    "0",
                    11,
                    time(),
                    111,
                    $qian,
                    $v['tctype'] . '套餐每天利息，编号' . $v["give_help_no"]
                ));
            }


            /*----------------------孟--------s---------*/
            $ussql = "select parents_ids from ld_user_account WHERE uname='" . $v['uname'] . "'";
            $db->query($ussql, 2);
            $ufather = $db->rs;
            $fatherarr = array_reverse(explode(',', rtrim(trim($ufather['parents_ids'], ','), ',')));
            /*    $msql = "select * from ld_prize_list WHERE help_id = " . $v['id'] . " and prize_option=54";
                $db->query($msql);
                $rs2 = $db->rs;
                if (!$rs2) {
                    return;
                }*/
            foreach ($fatherarr as $k2 => $v2) {
                if ($k2 > 3) {
                    $bili = $GLOBALARR['jjtjj'][3] * 0.01;
                } else {
                    $bili = $GLOBALARR['jjtjj'][$k2] * 0.01;
                }
                $tjj_money = $qian * $bili;
                $arrs['uid'] = $v2;
                $arrs['veid'] = $rt['id'];
                $arrs['prize_ltime'] = time();
                $arrs['grant_time'] = time();
                $arrs['prize_option'] = 54;
                $arrs['amount'] = $tjj_money;
                $bfb = ($bili * 100) . '%';
                $dstr = "第" . $ci . "天";
                $arrs['description'] = "会员【{$v['uname']}】利息分成的{$bfb}" . $dstr;
                $arrs['prize_status'] = 1; //默认发放
                $arrs['help_id'] = $v['id'];
                $arrs['lx_generation'] = $k2 + 1; // 第几代
                $arrs['state'] = 1; // 第几代
                $sql = getinsertsql($arrs, 'ld_prize_list');
                $db->query($sql, 5);
                //改变会员的奖金数
                $sql0 = "update ld_user_account set cash_ldprize = cash_ldprize + {$tjj_money} WHERE id=" . $v2;
                $db->sitedbexec($sql0);
            }
            /*----------------------孟-----------e-----------*/
        }
        $db->committransaction();
    } catch
    (PDOException $e) {
        $db->rollbacktransaction();
        a_bck("error");
    }
}

function fun_rfhO()
{
    global $db, $GLOBALARR, $member;
    $taocanday = array(
        "A" => 0,
        "B" => 1,
        "C" => 2,
        "D" => 3,
        "E" => 4
    );
    try {

        // 从提供帮助表中选择收益中的提供帮助用户等级值为0的收益次数小于最大收益次数的提供帮助记录
        $sql = "select amount,id,flx_time,give_help_time,give_help_no,benifit_times,uid,xf_type,tctype,tcdays from ld_give_help where status=0 and (flx_time<" . time() . " or flx_time is NULL) and benifit_times < tcdays and  tctype!='A' and id>=7677";
        $db->query($sql);
        $rs = $db->rs;
        if (!$rs) {
            return;
        }

        $db->begintransaction();
        $rt = fun_insertTime();
        foreach ($rs as $k => $v) {
            $rsm = $member->getuv1($v["uid"], "is_freezed");
            // 如果用户已被冻结跳过这次循环
            if ($rsm["is_freezed"] == 1)
                continue;
            if (empty($v['flx_time'])) {
                if (time() - $v['give_help_time'] < 24 * 3600) {
                    continue;
                }
            }
            if (date("Y-m-d") == date("Y-m-d", $v['flx_time'])) {
                continue;
            }



            $ukey = $taocanday[$v['tctype']];
            // 金额等于设定的根据用户等级不同的不同利息乘以提供帮助金额
            $qian = $GLOBALARR['allowtxall'][$ukey] / 100 * $v["amount"];
            // var_dump($qian);

            // 收益次数加一
            $ci = $v['benifit_times'] + 1;
            // 如果收益次数等于系统设定的收益次数，更新提供帮助表设定收益状态已结束
            if ($ci == $v["tcdays"]) {
                $db->lspre("update ld_give_help set status_value=1,status=1 where id=:t0", 4, array(
                    array(
                        ':t0'
                    ),
                    array(
                        $v['id']
                    )
                ));
                // 返还本金 减去冻结锁仓
                /**
                 * *****根据类型返还消费金额*************
                 */
                if ($v['xf_type'] == 1) {
                    writeaccount(array(
                        $v['uid'],
                        "0",
                        0,
                        time(),
                        9,
                        $v["amount"],
                        $v['tctype'] . '套餐结束返还到锁仓总量，编号' . $v["give_help_no"]
                    ));
                    writeaccount(array($v['uid'], "1", 23, time(), 230, $v["amount"], $v['tctype'] . '套餐结束冻结减去，编号' . $v["give_help_no"]));
                }
                if ($v['xf_type'] == 2) {
                    writeaccount(array(
                        $v['uid'],
                        "0",
                        11,
                        time(),
                        111,
                        $v["amount"],
                        $v['tctype'] . '套餐结束返还到锁仓收益，编号' . $v["give_help_no"]
                    ));
                    writeaccount(array($v['uid'], "1", 17, time(), 170, $v["amount"], $v['tctype'] . '套餐结束冻结减去，编号' . $v["give_help_no"]));
                }
                if ($v['xf_type'] == 3) {
                    writeaccount(array(
                        $v['uid'],
                        "0",
                        9,
                        time(),
                        91,
                        $v["amount"],
                        $v['tctype'] . '套餐结束返还到团队收益，编号' . $v["give_help_no"]
                    ));
                    writeaccount(array($v['uid'], "1", 18, time(), 180, $v["amount"], $v['tctype'] . '套餐结束冻结减去，编号' . $v["give_help_no"]));
                }


            }

            $db->lspre("update ld_give_help set benifit_times=benifit_times+1,benifit_amount=benifit_amount+:t1,flx_time=" . time() . " where id=:t0", 4, array(
                array(
                    ':t0',
                    ':t1'
                ),
                array(
                    $v['id'],
                    $qian
                )
            ));
            if ($qian > 0) {

                // 写入prize_list表
                fun_jjxx1(array(
                    $v['uid'],
                    $rt['id'],
                    time(),
                    51,
                    $qian,
                    '锁仓编号' . $v["give_help_no"] . '第' . $ci . '次',
                    $v["id"],
                    0,
                    1
                ));

                writeaccount(array(
                    $v['uid'],
                    "0",
                    11,
                    time(),
                    113,
                    $qian,
                    $v['tctype'] . '套餐每天利息，编号' . $v["give_help_no"]
                ));
            }

            $db->query("select * from ld_prize_list WHERE help_id={$v['id']} and prize_option = 54 and state=0");
            $userarr = $db->rs;
            foreach($userarr as $k2=>$v2){  //给用户加冻结钱
                $db->sitedbexec("update ld_user_account set cash_ldprize = cash_ldprize + {$v2['amount']} WHERE id=".$v2['uid']);
                $db->sitedbexec("update ld_prize_list set state = 1 WHERE id=".$v2['id']);
            }
        }

        $db->committransaction();
    } catch (PDOException $e) {
        $db->rollbacktransaction();
        a_bck("error");
    }
}

function ever_falixi()
{
    // A套餐
    $h = date("H");
    if ($h != 0) {
        return;
    }
    echo 'start';
    fun_rfhA();
    echo 'strat1';
    fun_rfhO();
    echo 'end';
    // A套餐之外的
}

// 分红sunli
function fun_rfh1()
{
    global $db, $GLOBALARR, $member, $r;
    try {
        $db->begintransaction();
        $rt = fun_insertTime();
        // 从提供帮助表中选择收益中的提供帮助用户等级值为0的收益次数小于最大收益次数的提供帮助记录
        $sql = "select ghelp_ulevel,amount,id,give_help_no,benifit_times,uid from ld_give_help where `status`<=1 and status_value=0 and " . time() . "-give_help_time>=24*3600*benifit_times and benifit_times<" . $GLOBALARR["perdays"];
        $db->query($sql);
        $rs = $db->rs;
        foreach ($rs as $k => $v) {
            $rsm = $member->getuv1($v["uid"], "is_freezed");
            // 如果用户已被冻结跳过这次循环
            if ($rsm["is_freezed"] == 1)
                continue;
            // 金额等于设定的根据用户等级不同的不同利息乘以提供帮助金额
            $qian = $GLOBALARR['allowtxall'] / 100 * $v["amount"];
            // 收益次数加一
            $ci = $v['benifit_times'] + 1;
            // 如果收益次数等于系统设定的收益次数，更新提供帮助表设定收益状态已结束
            if ($ci == $GLOBALARR["perdays"])
                $db->lspre("update ld_give_help set status_value=1 where id=:t0", 4, array(
                    array(
                        ':t0'
                    ),
                    array(
                        $v['id']
                    )
                ));
            // 增加收益次数，收益金额
            $db->lspre("update ld_give_help set benifit_times=benifit_times+1,benifit_amount=benifit_amount+:t1 where id=:t0", 4, array(
                array(
                    ':t0',
                    ':t1'
                ),
                array(
                    $v['id'],
                    $qian
                )
            ));
            if ($qian > 0) {
                // 写入prize_list表
                fun_jjxx1(array(
                    $v['uid'],
                    $rt['id'],
                    time(),
                    51,
                    $qian,
                    '提供帮助编号' . $v["give_help_no"] . '第' . $ci . '次',
                    $v["id"],
                    0
                ));
            }
        }

        $db->committransaction();
    } catch (PDOException $e) {
        $db->rollbacktransaction();
        a_bck("error");
    }
}

// 提供帮助利息
function fun_rfh2($give_help_id, $rt)
{
    global $db, $GLOBALARR, $member, $r;
    $sql = "select ghelp_ulevel,amount,id,give_help_no,benifit_times,uid from ld_give_help where `status`<=1 and status_value=0 and id=$give_help_id";
    $db->query($sql);
    $rs = $db->rs;
    foreach ($rs as $k => $v) {
        // 根据用户id查找账户冻结状态，已冻结的账户不增加利息
        $rsm = $member->getuv1($v["uid"], "is_freezed");
        if ($rsm["is_freezed"] == 1)
            continue;
        // 存款利息
        $qian = $GLOBALARR['allowtxall'] / 100 * $v["amount"];
        // 收益次数
        $ci = $v['benifit_times'] + 1;
        // 如果收益次数等于利息出局天数则更新收益状态为收益结束
        if ($ci == $GLOBALARR["jjlxt"])
            $db->lspre("update ld_give_help set status_value=1 where id=:t0", 4, array(
                array(
                    ':t0'
                ),
                array(
                    $v['id']
                )
            ));
        // 收益次数加一，收益金额增加
        $db->lspre("update ld_give_help set benifit_times=benifit_times+1,benifit_amount=benifit_amount+:t1 where id=:t0", 4, array(
            array(
                ':t0',
                ':t1'
            ),
            array(
                $v['id'],
                $qian
            )
        ));
        if ($qian > 0) {
            fun_jjxx1(array(
                $v['uid'],
                $rt['id'],
                time(),
                51,
                $qian,
                '消费编号' . $v["give_help_no"] . '第' . $ci . '次',
                $v["id"],
                0
            ));
        }
    }
}

function qianbao()
{
    global $CoinClient, $db;
    $coin = 'pbc';
    $json = $CoinClient->getinfo();

    if (!isset($json['version']) || !$json['version']) {
        echo '钱包连接失败' . "\n";
        return;
    }
    echo "钱包连接ok";
    $listtransactions = $CoinClient->listtransactions('*', 500, 0);
    echo 'listtransactions:' . count($listtransactions) . "\n";
    if (!empty($listtransactions)) {
        krsort($listtransactions);
        $a = 0;
        foreach ($listtransactions as $trans) {
            $a++;
            if ($trans['category'] == 'send') {
                continue;
            }
            echo $a;
            if (!$trans['account']) {
                echo 'empty account continue' . "\n";
                continue;
            }

            $db->query("select * from ld_user_account where uname='" . $trans['account'] . "' limit 1", 2);
            $user = $db->rs;
            // 是否存在该用户
            if (!$user) {
                echo 'empty dfcaccount continue' . "\n";
                continue;
            }

            // 查找是否已经接受过了
            $db->query("select * from ld_transfer_coin where txid='" . $trans['txid'] . "' and type=1 and is_cross=1 and coin='{$coin}' limit 1", 2);
            $jsinfo = $db->rs;
            if ($jsinfo) {
                // echo 'txid had found continue' . "\n";
                continue;
            }
            echo 'all check ok ' . "\n";
            if ($trans['category'] == 'receive') {
                // 接收信息
                echo 'start receive do:' . "\n";
                $sfee = 0;
                $true_amount = $trans['amount'];
                if ($trans['confirmations'] < 1) {
                    continue;
                } else {
                    echo 'confirmations full' . "\n";
                }
                try {
                    $db->begintransaction();
                    $price = getprice();
                    $money = round(($true_amount * $price), 2);
                    $db->query("select * from ld_transfer_coin where txid='" . $trans['txid'] . "' limit 1", 2);
                    $jsmes = $db->rs;
                    if ($jsmes) {
                        $sql3 = "update ld_transfer_coin set ctime='" . time() . "',is_cross=1 where id='" . $jsmes['id'] . "'";
                        $db->query($sql3, 4);
                    } else {
                        $sql4 = "insert into ld_transfer_coin(cuid,cuname,num,ctime,ctype,caddress,txid,cprice,ctotal,cfee,is_cross,type,coin)values(" . $user['id'] . ",'" . $user['uname'] . "'," . $true_amount . "," . time() . ",5,'" . $trans['address'] . "','" . $trans['txid'] . "'," . $price . "," . $money . ",0,1,1,'{$coin}')";
                        $db->sitedbexec($sql4);
                    }
                    // 增加账户的本金
                    writeaccount(array(
                        $user['id'],
                        "0",
                        23,
                        time(),
                        231,
                        $money,
                        '赞币转入现金|' . $trans['txid']
                    ));
                    $db->committransaction();
                } catch (PDOException $e) {
                    $db->rollbacktransaction();
                }
            }
        }
    }
}

function qianbao_btc()
{
    global $CoinClient_btc, $db;
    $coin = 'btc';
    $json = $CoinClient_btc->getinfo();

    if (!isset($json['version']) || !$json['version']) {
        echo '钱包连接失败' . "\n";
        return;
    }
    echo "钱包连接ok";
    $listtransactions = $CoinClient_btc->listtransactions('*', 500, 0);
    echo 'listtransactions:' . count($listtransactions) . "\n";
    if (!empty($listtransactions)) {
        krsort($listtransactions);
        $a = 0;
        foreach ($listtransactions as $trans) {
            $a++;
            if ($trans['category'] == 'send') {
                continue;
            }
            echo $a;
            if (!$trans['account']) {
                echo 'empty account continue' . "\n";
                continue;
            }

            $db->query("select * from ld_user_account where uname='" . $trans['account'] . "' limit 1", 2);
            $user = $db->rs;
            // 是否存在该用户
            if (!$user) {
                echo 'empty dfcaccount continue' . "\n";
                continue;
            }

            // 查找是否已经接受过了
            $db->query("select * from ld_transfer_coin where txid='" . $trans['txid'] . "' and type=1 and is_cross=1 and coin={$coin} limit 1", 2);
            $jsinfo = $db->rs;
            if ($jsinfo) {
                // echo 'txid had found continue' . "\n";
                continue;
            }
            echo 'all check ok ' . "\n";
            if ($trans['category'] == 'receive') {
                // 接收信息
                echo 'start receive do:' . "\n";
                $sfee = 0;
                $true_amount = $trans['amount'];
                if ($trans['confirmations'] < 1) {
                    continue;
                } else {
                    echo 'confirmations full' . "\n";
                }
                try {
                    $db->begintransaction();
                    $price = getprice();
                    $money = round(($true_amount), 2);
                    $db->query("select * from ld_transfer_coin where txid='" . $trans['txid'] . "' limit 1", 2);
                    $jsmes = $db->rs;
                    if ($jsmes) {
                        $sql3 = "update ld_transfer_coin set ctime='" . time() . "',is_cross=1 where id='" . $jsmes['id'] . "'";
                        $db->query($sql3, 4);
                    } else {
                        $sql4 = "insert into ld_transfer_coin(cuid,cuname,num,ctime,ctype,caddress,txid,cprice,ctotal,cfee,is_cross,type,coin)values(" . $user['id'] . ",'" . $user['uname'] . "'," . $true_amount . "," . time() . ",15,'" . $trans['address'] . "','" . $trans['txid'] . "',0," . $money . ",0,1,1,{$coin})";
                        $db->sitedbexec($sql4);
                    }
                    // 增加账户的本金
                    writeaccount(array(
                        $user['id'],
                        "0",
                        156,
                        time(),
                        1561,
                        $money,
                        '比特币转入|' . $trans['txid']
                    ));
                    $db->committransaction();
                } catch (PDOException $e) {
                    $db->rollbacktransaction();
                }
            }
        }
    }
}

function qianbao_ltc()
{
    global $CoinClient_ltc, $db;
    $coin = 'ltc';
    $json = $CoinClient_ltc->getinfo();

    if (!isset($json['version']) || !$json['version']) {
        echo '钱包连接失败' . "\n";
        return;
    }
    echo "钱包连接ok";
    $listtransactions = $CoinClient_ltc->listtransactions('*', 500, 0);
    echo 'listtransactions:' . count($listtransactions) . "\n";
    if (!empty($listtransactions)) {
        krsort($listtransactions);
        $a = 0;
        foreach ($listtransactions as $trans) {
            $a++;
            if ($trans['category'] == 'send') {
                continue;
            }
            echo $a;
            if (!$trans['account']) {
                echo 'empty account continue' . "\n";
                continue;
            }

            $db->query("select * from ld_user_account where uname='" . $trans['account'] . "' limit 1", 2);
            $user = $db->rs;
            // 是否存在该用户
            if (!$user) {
                echo 'empty dfcaccount continue' . "\n";
                continue;
            }

            // 查找是否已经接受过了
            $db->query("select * from ld_transfer_coin where txid='" . $trans['txid'] . "' and type=1 and is_cross=1 and coin='{$coin}' limit 1", 2);
            $jsinfo = $db->rs;
            if ($jsinfo) {
                // echo 'txid had found continue' . "\n";
                continue;
            }
            echo 'all check ok ' . "\n";
            if ($trans['category'] == 'receive') {
                // 接收信息
                echo 'start receive do:' . "\n";
                $sfee = 0;
                $true_amount = $trans['amount'];
                if ($trans['confirmations'] < 1) {
                    continue;
                } else {
                    echo 'confirmations full' . "\n";
                }
                try {
                    $db->begintransaction();
                    $price = getprice();
                    $money = round(($true_amount * $price), 2);
                    $db->query("select * from ld_transfer_coin where txid='" . $trans['txid'] . "' limit 1", 2);
                    $jsmes = $db->rs;
                    if ($jsmes) {
                        $sql3 = "update ld_transfer_coin set ctime='" . time() . "',is_cross=1 where id='" . $jsmes['id'] . "'";
                        $db->query($sql3, 4);
                    } else {
                        $sql4 = "insert into ld_transfer_coin(cuid,cuname,num,ctime,ctype,caddress,txid,cprice,ctotal,cfee,is_cross,type,coin)values(" . $user['id'] . ",'" . $user['uname'] . "'," . $true_amount . "," . time() . ",16,'" . $trans['address'] . "','" . $trans['txid'] . "',0," . $money . ",0,1,1,'{$coin}')";
                        $db->sitedbexec($sql4);
                    }
                    // 增加账户的本金
                    writeaccount(array(
                        $user['id'],
                        "0",
                        157,
                        time(),
                        1571,
                        $money,
                        '莱特币转入|' . $trans['txid']
                    ));
                    $db->committransaction();
                } catch (PDOException $e) {
                    $db->rollbacktransaction();
                }
            }
        }
    }
}

// 会员第一排单给代理发渠道奖
function fun_qdj($arr)
{
    global $db, $GLOBALARR;

    $uid = $arr[1];
    $db->query("select * from ld_address where adid=" . $uid . "", 2);
    $address = $db->rs;
    if (empty($address)) {
        return;
    }

    $pid = $address['fir_province_id'];
    $db->query("select * from ld_daili where dl_pid='" . $pid . "' and status=1 group by dluid");
    $list = $db->rs;
    if ($list) {
        foreach ($list as $key => $v) {
            $qian = $arr[0];
            if ($v['dluid'] == $uid) {
                continue;
            }
            // 渠道也捎上
            $ldamount = get_dz_amount($v['dluid']);
            if ($ldamount >= $qian) {
                $shaoshang = '';
                $qdj = $qian * $GLOBALARR['qdjbl'] / 100;
            } else {
                $shaoshang = '烧伤';
                $qdj = $ldamount * $GLOBALARR['qdjbl'] / 100;
            }
            fun_jjxx1(array(
                $v['dluid'],
                $arr[3],
                time(),
                55,
                $qdj,
                $arr[2] . '渠道奖消费排单' . $qian . '的' . $GLOBALARR['qdjbl'] . '%' . $shaoshang,
                $arr[4],
                0
            ));
        }
    }
}

// 固定利息
function fun_gdlx($give_help_id, $rt)
{
    global $db, $GLOBALARR, $member, $r;
    $sql = "select amount,id,give_help_no,benifit_times,uid from ld_give_help where `status`<=1 and status_value=0 and id=$give_help_id";
    $db->query($sql);
    $rs = $db->rs;

    foreach ($rs as $k => $v) {
        // 根据用户id查找账户冻结状态，已冻结的账户不增加利息
        $rsm = $member->getuv1($v["uid"], "is_freezed");
        if ($rsm["is_freezed"] == 1)
            continue; // 如果冻结跳出本次循环
        // 存款利息
        $qian = $GLOBALARR['allowtxall'] / 100 * $v["amount"];
        // 收益次数
        if ($v['benifit_times'] == 0) {
            $ci = $v['benifit_times'] + 1;
            // 用户帮助表收益次数加一，收益金额增加
            $db->lspre("update ld_give_help set benifit_times=benifit_times+1,benifit_amount=benifit_amount+:t1 where id=:t0", 4, array(
                array(
                    ':t0',
                    ':t1'
                ),
                array(
                    $v['id'],
                    $qian
                )
            )); //
            if ($qian > 0) {
                // 更新用户账户表，增加利息，利息收益
                $sql = "update ld_user_account set lx_amount=lx_amount+:t1,give_help_prize=give_help_prize+:t1,ua_benifit_times=ua_benifit_times+1,sy_amount=sy_amount+:t1 where id=:t0";

                $db->lspre($sql, 4, array(
                    array(
                        ':t0',
                        ':t1'
                    ),
                    array(
                        $v['uid'],
                        $qian
                    )
                ));
                // 写入prize_list表

                fun_jjxx1(array(
                    $v['uid'],
                    $rt['id'],
                    time(),
                    51,
                    $qian,
                    '排单编号' . $v["give_help_no"] . '记录利息',
                    $v["id"],
                    0
                ));
            }
        }
    }
}


/*
 function grant($money, $pid)
{
    global $db, $r, $GLOBALARR;
    // 项目的基本信息'
    $sql = "select * from ld_give_help WHERE id={$pid}";
    $db->query($sql, 2);
    $help = $db->rs;
    // 收益百分比 投资数
    switch ($help['tctype']) {
        case 'A':
            $tbl = $GLOBALARR['allowtxall'][0];
            $day = 1;
            break;
        case 'B':
            $tbl = $GLOBALARR['allowtxall'][1];
            $day = 15;
            break;
        case 'C':
            $tbl = $GLOBALARR['allowtxall'][2];
            $day = 30;
            break;
        case 'D':
            $tbl = $GLOBALARR['allowtxall'][3];
            $day = 60;
            break;
        case 'E':
            $tbl = $GLOBALARR['allowtxall'][4];
            $day = 90;
            break;
    }
    $reqlmoney = $money * ($tbl * 0.01) * $day;
    $time = strtotime(date('Y-m-d', time() + 24 * 3600));
    $grant_time = $time + (3600 * 24) * $help['tcdays'];
    $fatherarr = array_reverse(explode(',', rtrim(trim($r['parents_ids'], ','), ',')));
    $rt = fun_insertTime(); // 获取ld_grant_prize表最后一条记录，即今天的记录
    foreach ($fatherarr as $k => $v) {
        if ($k == 30) {
            break;
        }  //30个为止
        if ($k > 3) {
            $bili = $GLOBALARR['jjtjj'][3] * 0.01;
        } else {
            $bili = $GLOBALARR['jjtjj'][$k] * 0.01;
        }
        $tjj_money = $reqlmoney * $bili;
        $arrs['uid'] = $v;
        $arrs['veid'] = $rt['id'];
        $arrs['prize_ltime'] = time();
        $arrs['grant_time'] = $grant_time;
        $arrs['prize_option'] = 54;
        $arrs['amount'] = $tjj_money;
        $bfb = ($bili * 100) . '%';
        if ($help['tctype'] == 'A') {
            $dstr = "第1天";
        } else {
            $dstr = '';
        }
        $arrs['description'] = "会员【{$r['uname']}】利息分成的{$bfb}" . $dstr;
        $arrs['prize_status'] = 0;
        $arrs['help_id'] = $pid;
        $arrs['lx_generation'] = $k + 1; // 第几代
        $sql = getinsertsql($arrs, 'ld_prize_list');
        $db->query($sql, 5);
    }
}
 */
function grant($money, $pid)
{
    global $db, $r, $GLOBALARR;
    // 项目的基本信息'
    $sql = "select * from ld_give_help WHERE id={$pid}";
    $db->query($sql, 2);
    $help = $db->rs;
    // 收益百分比 投资数
    switch ($help['tctype']) {
        case 'B':
            $tbl = $GLOBALARR['allowtxall'][1];
            $day = 15;
            break;
        case 'C':
            $tbl = $GLOBALARR['allowtxall'][2];
            $day = 30;
            break;
        case 'D':
            $tbl = $GLOBALARR['allowtxall'][3];
            $day = 60;
            break;
        case 'E':
            $tbl = $GLOBALARR['allowtxall'][4];
            $day = 90;
            break;
    }
    $reqlmoney = $money * ($tbl * 0.01) * $day;
    $time = strtotime(date('Y-m-d', time() + 24 * 3600));
    $grant_time = $time + (3600 * 24) * $help['tcdays'];
    $fatherarr = array_reverse(explode(',', rtrim(trim($r['parents_ids'], ','), ',')));
    $rt = fun_insertTime(); // 获取ld_grant_prize表最后一条记录，即今天的记录
    foreach ($fatherarr as $k => $v) {
        if ($k == 30) {
            break;
        }  //30个为止
        if ($k > 3) {
            $bili = $GLOBALARR['jjtjj'][3] * 0.01;
        } else {
            $bili = $GLOBALARR['jjtjj'][$k] * 0.01;
        }
        $tjj_money = $reqlmoney * $bili;
        $arrs['uid'] = $v;
        $arrs['veid'] = $rt['id'];
        $arrs['prize_ltime'] = time();
        $arrs['grant_time'] = $grant_time;
        $arrs['prize_option'] = 54;
        $arrs['amount'] = $tjj_money;
        $bfb = ($bili * 100) . '%';
        $arrs['description'] = "会员【{$r['uname']}】利息分成的{$bfb}";
        $arrs['prize_status'] = 0;
        $arrs['help_id'] = $pid;
        $arrs['state'] = 0;
        $arrs['lx_generation'] = $k + 1; // 第几代
        $sql = getinsertsql($arrs, 'ld_prize_list');
        $db->query($sql, 5);
    }
}

function ff_dtj()
{
    global $db, $GLOBALARR, $member, $r;
    try {
        $db->begintransaction();         //事物开始
        // 检测发放日期动态奖
        $now = time();
        $sesql = "select * from ld_prize_list WHERE grant_time <= {$now} AND prize_status=0 AND prize_option = 54";
        $db->query($sesql);
        $rs = $db->rs;
        foreach ($rs as $k => $v) {
            $sql0 = "update ld_user_account set cash_ldprize = cash_ldprize + {$v['amount']} WHERE id=" . $v['uid'];
            $db->sitedbexec($sql0);  //改变会员的奖金数
            $sql1 = "update ld_prize_list set prize_status=1 WHERE id=" . $v['id'];
            $db->sitedbexec($sql1); // 改变ld_prize_list 的 状态 为1 已发放
        }
        $db->committransaction();    //关闭自动提交
    } catch (PDOException $e) {
        $db->rollbacktransaction();
        a_bck("error");
    }
}

// 注册赠送100个赞币，自注册之日起24小时后开始产出币，每天1%个，持续时间30天，赠送的币不可以提现。
function givepresentcoin()
{
    global $db, $GLOBALARR, $member, $r;
    try {
        $db->begintransaction();
        $rt = fun_insertTime();

        $sql = "select * from ld_user_account where is_freezed=0 and presentcoin>0";
        $db->query($sql);
        $rs = $db->rs;

        foreach ($rs as $k => $v) {
            $start = intval(time());
            // 注册24小时后
            if ($start < $v['regist_time'] + 24 * 3600) {
                continue;
            }
            // 註冊30天
            if ($start > $v['regist_time'] + 31 * 24 * 3600) {
                $db->query("update ld_user_account set presentcoin = 0 where uname='" . $v['uname'] . "'", 4);
                continue;
            }
            // 计算产生币
            $coin = $v['presentcoin'] * 0.01;
//             $db->query("update ld_user_account set cash_purse = cash_purse+'" . $coin . "' where uname='" . $v['uname'] . "'", 4);
//             $arrs['uname'] = $v['uname'];
//             $arrs['help_record_time'] = intval(time());
//             $arrs['get_envelope_type'] = 59;
//             $arrs['plus_amount'] = $coin;
//             $arrs['minus_amount'] = 0;
//             $arrs['uid'] = $v['id'];
//             $arrs['usable_amount'] = $v['bringcoin'] + $coin;
//             $arrs['description'] = "会员" . $v['uname'] . "赠送币产生赞币" . $coin;
//             $sql = getinsertsql($arrs, 'ld_help_record');
//             $db->query($sql, 5);
            writeaccount(array($v['id'], "0", 0, time(), 59, $coin, "会员" . $v['uname'] . "赠送币产生赞币" . $coin));
        }
        $db->committransaction();
    } catch (PDOException $e) {
        $db->rollbacktransaction();
        a_bck("error");
    }
}

?>